import { dealNodeClass, dom } from "../tool";

interface PropType {
    disabled?: boolean;
    list: (string | { key: string | number, title: string })[];
    value?: string | number | null | boolean;
    onChange?: (value: string | number | null | undefined | boolean) => void;
    target?: HTMLElement;
    style?: any;
    className?: string;
}

interface SwitchType {
    new(prop: PropType): SwitchType;
    onChange?: (value: string | number | boolean | null | undefined) => void;
    setValue: (value: string | number | boolean | null | undefined) => void;
    setDisabled: (arg: boolean) => void;
    value?: string | number | null | boolean;
    disabled: boolean;
    render: (node?: HTMLElement) => HTMLElement;
}

function Switch(this: SwitchType, prop: PropType) {
    const { disabled = false, list, value, onChange, target, style, className } = prop;
    this.onChange = onChange;
    const infos: any[] = new Array(2);
    const container = dom('div', { target, style, className: className ? "gkh-switch ".concat(className) : "gkh-switch" });

    if (list[0] instanceof Object) {
        infos[0] = {
            key: list[0].key,
            node: dom('div', { innerText: list[0].title, target: container })
        }
    } else {
        infos[0] = {
            key: list[0],
            node: dom('div', { innerText: list[0], target: container })
        }
    }
    if (list[1] instanceof Object) {
        infos[1] = {
            key: list[1].key,
            node: dom('div', { innerText: list[1].title, target: container })
        }
    } else {
        infos[1] = {
            key: list[1],
            node: dom('div', { innerText: list[1], target: container })
        }
    }
    infos[0].node.onclick = ()=>{
        this.setValue(infos[0].key);
        if(this.onChange) this.onChange(this.value);
    }
    infos[1].node.onclick = ()=>{
        this.setValue(infos[1].key);
        if(this.onChange) this.onChange(this.value);
    }
    this.setValue = (arg) => {
        this.value = arg;
        const b = arg == infos[0].key;
        dealNodeClass(infos[0].node, "gkh-switch-checked", b);
        dealNodeClass(infos[1].node, "gkh-switch-checked", !b);
    }
    this.setDisabled = (arg) => {
        this.disabled = arg;
        dealNodeClass(container, "gkh-disabled", arg);
    }
    this.setDisabled(disabled);
    this.setValue(value == undefined ? infos[0].key : value);
    this.render = (node) => {
        if (node) {
            node.appendChild(container);
        }
        return container;
    }
}

export default Switch as unknown as SwitchType;